using System;
using System.Text;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Oplaco.Core.BusinessLogicLayer;
using Oplaco.Core.Configuration;
using Oplaco.Web.UI;
using Oplaco.Web.DTO;
using Oplaco.Core.DAL;
using System.Web;
using System.Configuration;
using System.IO;



public partial class PostAd_aspx : System.Web.UI.Page
{
    private int adId;
   

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //set page title for SEO
            Oplaco.Core.Configuration.SiteSettings settings = Oplaco.Core.Configuration.SiteSettings.GetSharedSettings();
            Page.Title = settings.SiteName + " | " + SiteMap.CurrentNode.Title;

            //set titles 
            ddlCategories.TopCategoryLabel = GetLocalResourceObject("lblCategoryTitleResource1.Text").ToString();
            ddlCategories.SubCategoryLabel = GetLocalResourceObject("lblSubCategoryTitleResource1.Text").ToString();

            // Limit Description text.
            txtDescription.Attributes.Add("onkeydown", "textCounter(this,500);");
            txtDescription.Attributes.Add("onkeyup", "textCounter(this,500);");

            if (!Page.IsPostBack)
            {
                FileUpload1.Visible = settings.AllowImageUploads;
                FileUpload2.Visible = settings.AllowImageUploads;
                FileUpload3.Visible = settings.AllowImageUploads;

                ListItemCollection coll = new ListItemCollection();
                int integerValueForSale = (int)AdType.ForSale;
                int integerValueWanted = (int)AdType.Wanted;
                ListItem forsaleItem = new ListItem(String.Format(new AdTypeFormatProvider(), "{0}", AdType.ForSale), integerValueForSale.ToString());
                forsaleItem.Selected = true;
                ListItem wantedItem = new ListItem(String.Format(new AdTypeFormatProvider(), "{0}", AdType.Wanted), integerValueWanted.ToString());

                coll.Add(forsaleItem);
                coll.Add(wantedItem);

                ddlAdTypes.DataSource = coll;
                ddlAdTypes.DataBind();               

            }
        }
        catch (Oplaco.Exceptions.BusinessLayerException BLE)
        {
            CustomValidator val = new CustomValidator();
            val.IsValid = false;
            val.ErrorMessage = ConfigurationManager.AppSettings["GenericErrorMessage"];
            val.ValidationGroup = "LoginGroup";
            this.Page.Validators.Add(val);
            Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(BLE);
        }
        catch (Exception exception)
        {
            CustomValidator val = new CustomValidator();
            val.IsValid = false;
            val.ErrorMessage = ConfigurationManager.AppSettings["GenericErrorMessage"];
            val.ValidationGroup = "LoginGroup";
            this.Page.Validators.Add(val);
            Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(exception);
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e) {
        if (Page.IsValid)
        {
            try
            {
                SiteSettings s = SiteSettings.GetSharedSettings();
                int zipcode = 0;
                int subCategoryId = 0;
                string zipcodeExtension = String.Empty;
                object ozip = Profile.GetPropertyValue("Zipcode");
                object ozipex = Profile.GetPropertyValue("ZipcodeExtension");


                int memberId = 0;
                if (User.Identity.IsAuthenticated)
                {
                    if (!User.IsInRole("Users")) throw new Oplaco.Exceptions.PresentationLayerException("Only users in role 'Users' are allowed to post an ad");
                    UserDefinedProfile profile = new UserDefinedProfile();
                    memberId = Profile.MemberId; //(Int32)profile.GetPropertyValue("MemberId");
                }
                else {

                    Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(new Exception("No valid member to process the request")); //make sure admin or not logged in user processes order
                }
                
                if(ozip!=null) zipcode = Convert.ToInt32(ozip);
                if(ozipex!=null) zipcodeExtension = (String)ozipex;
                
                //process categories
                DropDownList ddlTopCategories = (DropDownList)ddlCategories.FindControl("ddlCategories");
                DropDownList ddlSubCategories = (DropDownList)ddlCategories.FindControl("ddlSubCategories");
                                
                if (!String.IsNullOrEmpty(ddlSubCategories.SelectedValue)) subCategoryId = Int32.Parse(ddlSubCategories.SelectedValue);
                int categoryId = Int32.Parse(ddlTopCategories.SelectedValue);
                if (subCategoryId > 0) categoryId = subCategoryId;

                //process other order values
                string title = Server.HtmlEncode(txtTitle.Text);
                string description = Server.HtmlEncode(txtDescription.Text);
                string url = txtUrl.Text;
                Decimal price = Decimal.Parse(txtPrice.Text);

                //get location if provided, if not, we use the location from the user.
                string location = Profile.ZipCode + Profile.ZipCodeExtension;


                //we do not show numDays in the GUI, if you want to use this, just add a dropdownlist to the page and get the value of that dropdown
                //for example : int numDays = Convert.ToInt32(ddlNumberOfDays.SelectedValue);
                int numDays = Convert.ToInt32(s.MaxAdRunningDays);

                //process ad type
                AdType adType = AdType.ForSale;
                if (Enum.IsDefined(typeof(AdType), ddlAdTypes.SelectedValue)) adType = (AdType)Enum.Parse(typeof(AdType), ddlAdTypes.SelectedValue);
                                               
                //process order
                adId = AdsDB.InsertAd(memberId,
                        categoryId,
                        title,
                        description,
                        url,
                        price,
                        location,
                        numDays,
                        AdLevel.Unspecified,
                        AdStatus.Unspecified,
                        adType);


                //now the photos                
                this.handlePhotoUpload(FileUpload1, true);
                this.handlePhotoUpload(FileUpload2, false);
                this.handlePhotoUpload(FileUpload3, false);
                            

                Response.Redirect("~/MyShop/MyAds.aspx");
            }
            catch (Oplaco.Exceptions.BusinessLayerException BLE)
            {
                CustomValidator val = new CustomValidator();
                val.IsValid = false;
                val.ErrorMessage = ConfigurationManager.AppSettings["GenericErrorMessage"];
                val.ValidationGroup = "LoginGroup";
                this.Page.Validators.Add(val);
                Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(BLE);
            }
            catch (Exception exception)
            {
                CustomValidator val = new CustomValidator();
                val.IsValid = false;
                val.ErrorMessage = ConfigurationManager.AppSettings["GenericErrorMessage"];
                val.ValidationGroup = "LoginGroup";
                this.Page.Validators.Add(val);
                Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(exception);
            }
        }
        
    }

    private void handlePhotoUpload(FileUpload uploadcontrol, bool isPreview) {

        SiteSettings settings = SiteSettings.GetSharedSettings();
        // Specify the path on the server to
        // save the uploaded file to.
        string savePath = settings.ServerPhotoUploadDirectory;

        try
        {
            if(this.adId==0) Oplaco.Exceptions.AppService.ProcessAndNotifyBusinessLayerException(new Exception("No advertisement was made"));


            // Before attempting to save the file, verify
            // that the FileUpload control contains a file.
            if (uploadcontrol.HasFile)
            {
                // Get the name of the file to upload.
                string fileName = Server.HtmlEncode(uploadcontrol.FileName);

                // Get the extension of the uploaded file.
                string extension = System.IO.Path.GetExtension(fileName);

                // Allow only files with .doc or .xls extensions
                // to be uploaded.

                if (Array.IndexOf(settings.AllowedImageTypes, extension) >= 0)
                {
                    // Append the name of the file to upload to the path.
                    savePath = "/" + savePath + "/" + fileName;

                    // Call the SaveAs method to save the 
                    // uploaded file to the specified path.
                    // This example does not perform all
                    // the necessary error checking.               
                    // If a file with the same name
                    // already exists in the specified path,  
                    // the uploaded file overwrites it.
                    uploadcontrol.SaveAs(HttpContext.Current.Server.MapPath("~" + savePath));
                    byte[] rawData = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~" + savePath));
                    PhotosDB.InsertPhoto(adId, rawData, PhotosDB.ResizeImageFile(rawData, PhotoSize.Medium), PhotosDB.ResizeImageFile(rawData, PhotoSize.Small), isPreview);
                }
                else
                {
                    // Notify the user why their file was not uploaded.
                    string message = "Your ad had been created, but your photo was not uploaded because it does not have a .png, .gif or .jpg extension.<br/> You can add your photo in your shop section";
                    Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(new Exception(message));
                }

            }
        }
        catch (Oplaco.Exceptions.BusinessLayerException BLE)
        {
            CustomValidator val = new CustomValidator();
            val.IsValid = false;
            val.ErrorMessage = ConfigurationManager.AppSettings["GenericErrorMessage"];
            val.ValidationGroup = "LoginGroup";
            this.Page.Validators.Add(val);
            Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(BLE);
        }
        catch (Exception exception)
        {
            CustomValidator val = new CustomValidator();
            val.IsValid = false;
            val.ErrorMessage = ConfigurationManager.AppSettings["GenericErrorMessage"];
            val.ValidationGroup = "LoginGroup";
            this.Page.Validators.Add(val);
            Oplaco.Exceptions.AppService.ProcessAndNotifyPresentationLayerException(exception);
        }

    }
}
